using System;
using System.IO;
using System.Net;
using System.Security.Cryptography;
using System.Text;

namespace dlw.S3Examples
{
    [TestClass]
    class VerySimpleExample
    {
        private static log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
        // VerySimpleExample SimpleListBuckets 04KPY2YGG73ENMP9A2G2 pRJKMISVZepQhkafhsG3djXEs9AOep/svSNamnqX
        [TestMethod]
        public void SimpleListBuckets(string awsId, string secretId)
        {
            // here is the basic Http Web Request
            string url = "http://s3.amazonaws.com";
            HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
            request.Method = "GET";

            WebHeaderCollection headers = (request as HttpWebRequest).Headers;

            // the canonical string combines the request's data
            // with the current time
            string httpDate 
                = DateTime.UtcNow.ToString("ddd, dd MMM yyyy HH:mm:ss "
                ) + "GMT"; ;
            headers.Add("x-amz-date", httpDate);
            // our request is very simple, so we can hard-code the string
            string canonicalString = "GET\n\n\n\nx-amz-date:" + httpDate + "\n/";

            // now encode the canonical string
            Encoding ae = new UTF8Encoding();
            // create a hashing object
            HMACSHA1 signature = new HMACSHA1();
            // secretId is the hash key
            signature.Key = ae.GetBytes(secretId);
            byte[] bytes  = ae.GetBytes(canonicalString);
            byte[] moreBytes = signature.ComputeHash(bytes);
            // convert the hash byte array into a base64 encoding
            string encodedCanonical = Convert.ToBase64String(moreBytes);

            // finally, this is the Authorization header.
            headers.Add("Authorization", "AWS " + awsId + ":" + encodedCanonical);

            HttpWebResponse response;
            response = request.GetResponse() as HttpWebResponse;

            // read the response stream and put it into a byte array
            Stream stream =  response.GetResponseStream() as Stream;
            byte[] buffer = new byte[32 * 1024];
            int nRead =0;
            MemoryStream ms = new MemoryStream();
            do
            {
                nRead = stream.Read(buffer, 0, buffer.Length);
                ms.Write(buffer, 0, nRead);
            } while (nRead > 0);

            // convert read bytes into string
            ASCIIEncoding encoding = new ASCIIEncoding();
            string responseString = encoding.GetString(ms.ToArray());

            log.Info(responseString);
        }

    }
}
